<template>
  <div class="flex h-full">
    <div class=""><Ueditor ref="ueditorRef" /></div>
    <div class="flex flex-col justify-between h-full p-2 overflow-hidden w-247px">
      <div class="source-componet-item-title mb-2">设计器</div>
      <div class="flex-auto pr-1 mb-2 overflow-y-scroll">
        <ul>
          <li
            class="p-1 mb-1 overflow-hidden cursor-pointer source-componet-item"
            v-for="(item, index) in fieldList"
            :key="index"
            @click="handleClick(item)"
          >
            <EIcon prefix="" :name="item.icon" />
            {{ item.label }}
          </li>
        </ul>
      </div>
      <div class="flex justify-center gap-2">
        <a-button type="primary" @click="handleOk" :loading="loading">保存</a-button>
        <a-button @click="handleCancel">关闭</a-button>
      </div>
    </div>

    <ModuleFieldSelectModal
      v-model:visible="moduleFieldSelectModalVisible"
      :data="moduleFieldData"
      @success="handleModuleFieldSelectSuccess"
      v-if="moduleFieldSelectModalVisible"
      :zIndex="2000"
    />

    <NestSheetModal
      v-model:visible="nestSheetVisible"
      :data="nestSheetData"
      @success="handleNestSheetSuccess"
      v-if="nestSheetVisible"
      :zIndex="2000"
      :mode="nestTableMode"
    />

    <MacroFormulaCtlModal
      v-model:visible="macroFormulaVisible"
      :data="macroFormulaData"
      @success="handleMacroFormulaSuccess"
      v-if="macroFormulaVisible"
      :zIndex="2000"
    />

    <MacroIconCtlModal
      v-model:visible="macroIconVisible"
      :data="macroIconData"
      @success="handleMacroIconSuccess"
      v-if="macroIconVisible"
      :zIndex="2000"
    />

    <ExprModal @register="registerModal" @success="handleExprSuccess" />

    <CommonDrawer @register="registerDrawer" @success="handleSuccess" :zIndex="2000" />
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, nextTick, h } from 'vue';
  import { message } from 'ant-design-vue';
  import Ueditor from '/@/components/Ueditor/index.vue';
  import { useRouter } from 'vue-router';
  import EIcon from './icon';
  import { fieldList } from './ueditorFormDesigner.data';
  import { ajaxPost, myMsg } from '/@/utils/utils';
  import ModuleFieldSelectModal from '/@/views/formDesigner/ui/cloud/common/moduleFieldSelect/ModuleFieldSelectModal.vue';
  import NestSheetModal from '/@/views/formDesigner/ui/cloud/common/nestSheet/NestSheetModal.vue';
  import MacroFormulaCtlModal from '/@/views/formDesigner/ui/cloud/common/macroFormulaCtl/MacroFormulaCtlModal.vue';
  import MacroIconCtlModal from '/@/views/formDesigner/ui/cloud/common/macroIconCtl/MacroIconCtlModal.vue';
  import CommonDrawer from '/@/views/pages/managerPage/pageComponent/common/CommonDrawer.vue';

  import {
    convertModuleFieldSelectDesc,
    convertModuleFieldSelectDescRevise,
    convertNestSheetDesc,
    convertNestSheetDescRevise,
  } from '/@/api/macro/macro';
  import {
    checkUeditorForm,
    updateUeditorForm,
    getFormContent,
  } from '/@/api/formDesign/formDesign';

  import { ExprModal } from '/@/components/CustomComp';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useUserStore } from '/@/store/modules/user';
  import { getToken } from '/@/utils/auth';
  import { useDrawer } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';

  const { createMessage, createConfirm } = useMessage();
  const { currentRoute } = useRouter();
  const { t } = useI18n();
  const state = ref<Recordable>({
    formCode: '',
  });
  const loading = ref(false);
  const ueditorRef = ref<any>(null);
  const userStore = useUserStore();

  const moduleFieldSelectModalVisible = ref(false);
  const moduleFieldData = ref({});

  const nestSheetVisible = ref(false);
  const nestSheetData = ref<Recordable>({});
  const nestTableMode = ref('');

  const macroFormulaVisible = ref(false);
  const macroFormulaData = ref<Recordable>({});

  const macroIconVisible = ref(false);
  const macroIconData = ref<Recordable>({});

  //写入
  const handleWrite = async (content) => {
    await nextTick();
    const { setContent, hasContent } = ueditorRef.value;
    setTimeout(() => {
      if (content) {
        setContent(content);
      }
    }, 500);
  };
  //聚焦
  const handleFocus = () => {
    const { setFocus } = ueditorRef.value;
    setFocus();
  };
  //获取
  const handleGetContent = () => {
    const { getAllHtml, getContent } = ueditorRef.value;
    return getContent();
  };
  //插入
  const handleInsertHtml = (value) => {
    const { insertHtml } = ueditorRef.value;
    insertHtml(value);
  };
  const handleExec = (method) => {
    const { exec } = ueditorRef.value;
    exec(method);
  };

  function handleClick({ type }) {
    if (
      type == 'textarea' ||
      type == 'select' ||
      type == 'checkbox' ||
      type == 'button' ||
      type == 'calculation' ||
      type == 'calendar'
    ) {
      handleExec(type);
    } else if (type == 'date') {
      handleExec('calendar');
    } else if (type == 'input') {
      handleExec('text');
    } else if (type == 'radio') {
      handleExec('radios');
    } else if (type == 'calculation') {
      handleExec('calculation');
    } else {
      handleExec('macros');
    }
  }

  // 初始化
  const getContentOfForm = async () => {
    const params = {
      ...state.value,
    };
    const data = await getFormContent(params);
    await handleWrite(data?.content);
  };

  const handleRefresh = async () => {
    getContentOfForm();
  };

  const fetch = async () => {
    await nextTick();

    const { query } = currentRoute.value as any;
    state.value.formCode = query?.formCode;

    getContentOfForm();

    let newWindow = window as any;
    newWindow.ajaxPost = ajaxPost;
    newWindow.openModuleFieldSelectModal = openModuleFieldSelectModal;
    newWindow.getServerUrl = getServerUrl;
    newWindow.getToken = getToken;
    newWindow.getContent = handleGetContent;
    newWindow.myMsg = myMsg;
    newWindow.openNestSheetModal = openNestSheetModal;
    newWindow.openMacroFormulaModal = openMacroFormulaModal;
    newWindow.openMacroIconModal = openMacroIconModal;
    newWindow.handleEditButtonProps = handleEditButtonProps;
    newWindow.handleEditExpr = handleEditExpr;
    newWindow.isExprEnabled = isExprEnabled;
  };

  onMounted(fetch);

  function getServerUrl() {
    return userStore.getServerUrl;
  }

  function isExprEnabled() {
    let serverInfo = userStore.getServerInfo;
    return serverInfo.isExprEnabled;
  }

  async function handleModuleFieldSelectSuccess(data) {
    console.log('handleModuleFieldSelectSuccess data', data);
    let d = await convertModuleFieldSelectDesc(data);
    console.log('handleModuleFieldSelectSuccess d', d);
    try {
      let frames = window.frames;
      console.log('frames', frames);
      for (var i in frames) {
        // window.opener.setSequence(json, formCode.options[formCode.selectedIndex].text + "_" + otherShowField.options[otherShowField.selectedIndex].text);
        if (frames[i] && typeof frames[i].setSequence == 'function') {
          console.log('setSequence founded', frames[i]);
          frames[i].setSequence(d.desc, '');
          break;
        }
      }
      open.value = false;
    } catch (e) {
      console.log(e);
    }
  }

  async function openModuleFieldSelectModal(formCode, desc = '') {
    if (desc != '') {
      let params = {
        desc: desc,
      };
      let data = await convertModuleFieldSelectDescRevise(params);
      console.log('openModuleFieldSelectModal data', data);
      moduleFieldData.value = data;
    }
    moduleFieldSelectModalVisible.value = true;
  }

  const handleNestSheetSuccess = async (data) => {
    let d = await convertNestSheetDesc(data);
    console.log('handleNestSheetSuccess d', d);
    try {
      let frames = window.frames;
      console.log('frames', frames);
      for (var i in frames) {
        if (frames[i] && typeof frames[i].setSequence == 'function') {
          console.log('setSequence founded', frames[i]);
          frames[i].setSequence(d.desc, '');
          break;
        }
      }
      nestSheetVisible.value = false;
    } catch (e) {
      console.log(e);
    }
  };

  async function openNestSheetModal(formCode, desc = '', mode = 'nest_sheet') {
    if (desc != '') {
      let params = {
        desc: desc,
      };
      let data = await convertNestSheetDescRevise(params);
      console.log('openNestSheetModal data', data);
      nestSheetData.value = data;
    }
    nestSheetVisible.value = true;
    nestTableMode.value = mode;
  }

  const handleMacroFormulaSuccess = async (data) => {
    console.log('handleMacroFormulaSuccess data', data);
    try {
      let frames = window.frames;
      console.log('frames', frames);
      for (var i in frames) {
        if (frames[i] && typeof frames[i].setSequence == 'function') {
          console.log('setSequence founded', frames[i]);
          data.code = data.sel;
          delete data.sel;
          console.log('data', data);
          frames[i].setSequence(JSON.stringify(data), '');
          break;
        }
      }
      macroFormulaVisible.value = false;
    } catch (e) {
      console.log(e);
    }
  };

  async function openMacroFormulaModal(formCode, desc = {}) {
    console.log('openMacroFormulaModal formCode', formCode);
    macroFormulaVisible.value = true;
    if (desc != '') {
      macroFormulaData.value = desc;
    }
  }

  const handleMacroIconSuccess = async (data) => {
    console.log('handleMacroIconSuccess data', data);
    try {
      let frames = window.frames;
      console.log('frames', frames);
      for (var i in frames) {
        if (frames[i] && typeof frames[i].setSequence == 'function') {
          console.log('setSequence founded', frames[i]);
          data.code = data.sel;
          delete data.sel;
          console.log('data', data);
          frames[i].setSequence(JSON.stringify(data), '');
          break;
        }
      }
      macroIconVisible.value = false;
    } catch (e) {
      console.log(e);
    }
  };

  async function openMacroIconModal(formCode, desc = {}) {
    console.log('openMacroIconModal formCode', formCode);
    macroIconVisible.value = true;
    if (desc != '') {
      macroIconData.value = desc;
    }
  }

  const handleOk = async () => {
    try {
      const content = await handleGetContent();
      const params = {
        ...state.value,
        content,
      };
      loading.value = true;

      const data = await checkUeditorForm(params);
      if (data.msg) {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('common.prompt')),
          // content: () => h('span', data.msg),
          content: data.msg,
          onOk: async () => {
            await updateUeditorForm(params);
            message.success(t('common.opSuccess'));
          },
        });
      } else {
        await updateUeditorForm(params);
        message.success(t('common.opSuccess'));
        // fetch();
      }
    } catch (error) {
      console.error(error);
    } finally {
      loading.value = false;
    }
  };
  const handleCancel = () => {
    window.close();
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const handleEditButtonProps = (data) => {
    console.log('handleEdit data', data);
    openDrawer(true, {
      isUpdate: true,
      formCode: currentRoute.value.query.formCode,
      moduleCode: currentRoute.value.query.formCode,
      position: 'form',
      record: data,
    });
  };

  const handleSuccess = (data) => {
    try {
      let frames = window.frames;
      console.log('frames', frames);
      for (var i in frames) {
        if (frames[i] && typeof frames[i].setButtonScript == 'function') {
          console.log('setSequence founded', frames[i]);
          console.log('data', data);
          frames[i].setButtonScript(JSON.stringify(data), '');
          break;
        }
      }
    } catch (e) {
      console.log(e);
    }
  };

  const [registerModal, { openModal }] = useModal();

  const handleEditExpr = (expr) => {
    // visible.value = true;
    // console.log('handleEdit visible', visible.value);
    openModal(true, {
      expr: expr, // || '表单 表单1 * 表单11*表单12+SUM(1,2) AVG(99,21) IF()'
      isUpdate: true,
    });
  };

  const handleExprSuccess = (val) => {
    console.log('handleSuccess-FormulaInput', val);
    try {
      let frames = window.frames;
      console.log('frames', frames);
      for (var i in frames) {
        if (frames[i] && typeof frames[i].setExpr == 'function') {
          console.log('handleExprSuccess founded', frames[i]);
          frames[i].setExpr(val);
          break;
        }
      }
    } catch (e) {
      console.log(e);
    }
  };

  defineExpose({
    handleRefresh,
  });
</script>

<style scoped>
  #editor {
    height: calc(100vh - 100px);
    width: calc(100% - 200px);
  }
  .source-componet-item,
  .source-componet-item-title {
    border: 1px solid #d9d9d9;
    padding: 8px 10px;
    border-radius: 4px;
  }
  .source-componet-item:hover {
    border-color: #0960bd;
    color: #0960bd;
    background-color: rgba(9, 96, 189, 0.06);
  }
</style>
